package com.wyh.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    //创建单例ObjectMapper对象
    private final static ObjectMapper OBJECT_MAPPER;

    //将构造方法私有化
    private JacksonUtil(){

    }

    //饿汉模式，在类加载的时候就实例化对象
    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    //获取ObjectMapper对象
    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    /**
     * 学习springBoot中的json代码风格，减少代码冗余
     */

    /**
     * tryParse方法
     */
    private static <T> T tryParse(Callable<T> parser){
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check){
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
            throw new IllegalStateException(var4);
        }
    }

    /**
     * 序列化
     */
    public static String writeValueAsString(Object object){
        return tryParse(()->{
            return OBJECT_MAPPER.writeValueAsString(object);
        });
    }

    /**
     * 反序列化
     */
    public static <T> T readValue(String content, Class<T> valueType){
        return tryParse(()->{
            return OBJECT_MAPPER.readValue(content,valueType);
        });
    }

    /**
     * List反序列化
     */
    public static <T> T readListValue(String content, Class<?> paramClasses){
        JavaType javaType = OBJECT_MAPPER.getTypeFactory()
                .constructParametricType(List.class, paramClasses);
        return tryParse(()->{
            return OBJECT_MAPPER.readValue(content, javaType);
        });
    }


}
